<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { zpGetJobList } from '../api/jobs'
import { useJobsStore } from '../store'
import { showInfoMsg, showErrorMsg } from '../utils/helpers'
import cityData from '../city.json'
const jobStore = useJobsStore()

const isLoading = ref(false)
const buttonText = ref('获取职位数据')
const cityMap = new Map<string, number>()
cityMap.set('全国', 100010000)

onMounted(() => {
  cityData.zpData.cityGroup.forEach(item => {
    item.cityList.forEach(city => {
      cityMap.set(city.name, city.code)
    })
  })
})

const formData = ref({
  cityName: '全国',
  city: 100010000, // 城市代码
  pageSize: 30,
  page: 1, // 当前页
  query: '前端'
})


const rules = {
  cityName: [
    // { required: true, message: '城市必填', trigger: 'change'},
    {
      validator: (_: any, val: any, callback: (...params: any) => void) => {
        const city = val.trim()
        if (!cityMap.has(city)) {
          callback(new Error('城市不存在'))
          return
        }
        formData.value.city = cityMap.get(city) as number
        callback()
      }, 
      trigger: 'change',
      message: '城市名无效'
    }
  ]
}

const resetBtnText = () => {
  buttonText.value = '抓取职位数据'
}

// 抓取职位列表数据
const getJobList = () => {
  if (!isLoading.value) {
    resetBtnText()
    return
  }
  buttonText.value = '正在抓取，请稍后...'
  zpGetJobList({ ...formData.value, query: encodeURI(formData.value.query) })
    .then(res => {
      if (res.zpData.hasMore) {
        jobStore.appenJobs(res.zpData.jobList)
        formData.value.page += 1
        return setTimeout(getJobList, Math.random() * 5000 + 10000)
      }
      showInfoMsg('抓取完成')
      resetBtnText()
      isLoading.value = false
    })
    .catch(err => {
      showErrorMsg((err as Error).message)
      resetBtnText()
      isLoading.value = false
    })
}

const startGetJobs = () => {
  jobStore.clearJobs()
  formData.value.page = 1
  isLoading.value = true
  getJobList()
}

const stopGetJobs = () => {
  isLoading.value = false
  resetBtnText()
}
</script>

<template>
  <div v-loading="isLoading">
    <el-form :model="formData" label-width="120px" :rules="rules">
      <el-form-item label="城市名" prop="cityName">
        <el-input v-model="formData.cityName"/>
      </el-form-item>
      <el-form-item label="城市代码">
        <el-input v-model="formData.city" disabled />
      </el-form-item>
      <el-form-item label="页码">
        <el-input v-model="formData.page" disabled />
      </el-form-item>
      <el-form-item label="关键词">
        <el-input v-model="formData.query" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="startGetJobs">{{ buttonText }}</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="btns">
    <el-button v-if="isLoading" type="warning" size="large" @click="stopGetJobs">停止抓取</el-button>
  </div>
</template>

<style lang="scss" scoped>
.btns {
  margin-block: 30px;
  text-align: center;
}</style>